package com.simple.jdbc.core.config;

import com.simple.jdbc.core.pojo.Configuration;
import com.simple.jdbc.core.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * parse 映射配置文件解析 -》 mapstatement对象 -》 configuration集合
 */
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream resourceAsStream) throws DocumentException {

        String selectXpath = "//select";

        Document document = new SAXReader().read(resourceAsStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        /**
         <select id="selectOne" resultType="org.demo.pojo.Employee" prarameterType="org.demo.pojo.Employee">
         select * from employee where id = #{id} and last_name = #{lastName}
         </select>
         */

        buildMappedStatement(rootElement, selectXpath, namespace);


    }

    private void buildMappedStatement(Element rootElement, String selectXpath, String namespace) {
        List<Node> selectList = rootElement.selectNodes(selectXpath);
        for (Node node : selectList) {
            Element element = (Element) node;
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");

            String sql = element.getTextTrim();
            //封装MappedStatement对象
            String statementId = namespace + "." + id;
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setStatementId(statementId);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setSql(sql);
            //todo 这里暂时写死作为select类型  应该进行判断
            mappedStatement.setSqlCommandType("select");

            //
            configuration.addMappedStatement(mappedStatement);
        }
    }

}
